package servlet;

import dao.BookDAO;
import model.Book;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;
@WebServlet("/BookServlet")
public class BookServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");

        if ("add".equals(action)) {
            String title = request.getParameter("title");
            String author = request.getParameter("author");
            String publisher = request.getParameter("publisher");
            int year = Integer.parseInt(request.getParameter("year"));

            Book book = new Book(0, title, author, publisher, year);
            BookDAO.addBook(book);
            response.sendRedirect("BookServlet");  // 重定向到 GET 请求

        } else if ("update".equals(action)) {
            int id = Integer.parseInt(request.getParameter("id"));
            String title = request.getParameter("title");
            String author = request.getParameter("author");
            String publisher = request.getParameter("publisher");
            int year = Integer.parseInt(request.getParameter("year"));

            Book book = new Book(id, title, author, publisher, year);
            BookDAO.updateBook(book);
            response.sendRedirect("BookServlet");  // 重定向到 GET 请求

        } else if ("delete".equals(action)) {
            int id = Integer.parseInt(request.getParameter("id"));
            BookDAO.deleteBook(id);
            response.sendRedirect("BookServlet");  // 重定向到 GET 请求
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Book> books = BookDAO.findBooks();
        request.setAttribute("books", books);
        request.getRequestDispatcher("books.jsp").forward(request, response);
    }
}